package com.lnyt.controller;

import java.io.*;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lnyt.pojo.weixin.ReqAllMessage;
import com.lnyt.pojo.weixin.ResTextMessage;
import com.lnyt.service.ChatRobotService;
import com.lnyt.util.LogUtil;
import com.lnyt.util.CheckUtil;
import com.lnyt.util.XmlUtil;
import com.lnyt.util.factroy.WeixinResFactroy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@CrossOrigin(origins = "*")
@RequestMapping(value = "/weixin")
public class WeixinMessage {
    @Resource
    private ChatRobotService chatRobotService;

    // Http
    @RequestMapping(value = "")
    public void getMessage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        LogUtil.log4j2().info("Request url: lnyt/weixin");
        Map<String, String[]> prams = request.getParameterMap();
        //Map prams = request.getParameterMap();

        // request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (CheckUtil.checkSignature(prams)) {
            // 返回echostr
            if (prams.containsKey("echostr")) {
                response.getWriter().write(prams.get("echostr")[0]);
                LogUtil.log4j2().info("Host pass");
                return;
            } else {
                // test
                Reader br = request.getReader();
                Writer bw = response.getWriter();

                try {
                    ReqAllMessage weixinMsg = (ReqAllMessage)XmlUtil.fomatXml(br, ReqAllMessage.class);

                    // 根据消息类型处理
                    switch (weixinMsg.getMsgType()) {
                        case "text":
                            String reqText = weixinMsg.getContent();
                            String openID = weixinMsg.getFromUserName();
                            String resText = chatRobotService.getRobotMessage(reqText, "", openID);

                            ResTextMessage textMessage = WeixinResFactroy.creatorText(weixinMsg, resText);

                            String xmlText = XmlUtil.toXml(textMessage, "UTF-8");
                            bw.write(xmlText);
                            LogUtil.log4j2().info("Response url: lnyt/weixin");
                            break;

                        default:
                            break;
                    }

                } catch (Exception exc) {
                    LogUtil.log4j2().warn(exc.getMessage());
                }
            }
        }

        return;
    }

}
